/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.repository.adaptoritem.sqlsnippetprocessor;

import com.inspur.edp.cef.api.repository.GspDbType;
import com.inspur.edp.cef.repository.adaptoritem.DBExtendInfo;
import com.inspur.edp.cef.repository.exception.CefRepositoryException;
import com.inspur.edp.cef.repository.sqlgenerator.*;
import com.inspur.edp.cef.spi.jsonser.base.StringUtils;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.HashMap;
import java.util.Map;

public class SqlGeneratorFactory {
    private  static Map<GspDbType, ISqlGenerator> processorMap=new HashMap<>();
    public static ISqlGenerator getSqlProcessor(GspDbType gspDbType) {
        if(processorMap.containsKey(gspDbType))
            return processorMap.get(gspDbType);
        ISqlGenerator sqlGenerator = null;
        switch (gspDbType){
            case Oracle:
            case DM:
            case DB2:
            case OceanBase:
                sqlGenerator = new OraSqlGenerator();
                break;
            case HighGo:
            case PgSQL:
            case OpenGauss:
                sqlGenerator = new PgSqlGenerator();
                break;
            case MySQL:
            case SQLServer:
                sqlGenerator = new SqlSvrSqlGenerator();
                break;
            case Oscar:
                sqlGenerator = new ShenTongSqlGenerator();
                break;
            case Kingbase:
                sqlGenerator = new KingbaseSqlGenerator();
                break;
            case Unknown:
                try {
                    DBExtendInfo dbExtendInfo = SpringBeanUtils.getBean(DBExtendInfo.class);
                    if(dbExtendInfo != null && !StringUtils.isNullOrEmpty(dbExtendInfo.getSqlGenerateClass())){
                        Class sqlGeneratorClass = Class.forName(dbExtendInfo.getSqlGenerateClass());
                        sqlGenerator = (ISqlGenerator) sqlGeneratorClass.newInstance();
                        break;
                    }
                }
                catch (Exception ex){
                    throw new CefRepositoryException("未识别的数据库类型，未找到对应处理器", ex);
                }
            default:
                sqlGenerator = new PgSqlGenerator();
                break;
        }
        processorMap.put(gspDbType,sqlGenerator);
        return sqlGenerator;
    }
}
